package com.example.foo.api.web.ftt;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.ad.api.utils.SmsSendUtils;
import com.ruoyi.common.core.domain.AjaxResult;
import com.example.core.PageResult;
import com.example.core.Pageable;
import com.example.foo.api.boot.TokenHelper;
import com.example.foo.ftt.FttUserHelper;
import com.example.foo.ftt.model.FttUser;
import com.example.foo.ftt.query.FttUserQuery;
import com.example.foo.ftt.service.FttUserFacadeService;
import com.example.foo.ftt.service.FttUserService;
import com.example.foo.fttcard20220715.model.FttCard20220715;
import com.example.foo.fttcard20220715.service.FttCard20220715Service;
import com.example.util.RegexSnippetUtils;

@org.springframework.web.bind.annotation.RestController
public class FttUserAction {

	private final FttCard20220715Service fttCard20220715Service;
	private final FttUserService fttUserService;
	private final FttUserFacadeService fttUserFacadeService;

	public FttUserAction(FttCard20220715Service fttCard20220715Service,
			FttUserService fttUserService,
			FttUserFacadeService fttUserFacadeService) {
		this.fttCard20220715Service = fttCard20220715Service;
		this.fttUserService = fttUserService;
		this.fttUserFacadeService = fttUserFacadeService;
	}

	@GetMapping(path = "/api/fttusers")
	public AjaxResult listFttUsers(FttUserQuery fttUserQuery, Pageable pageable, @RequestParam(name = "fromUserIdUntilLeaf", required = false) Long fromUserIdUntilLeaf) {
		Long loginedUserId = TokenHelper.verifyToken();

		Long referralParentUserId = fttUserQuery.getReferralParentUserId();
		if (referralParentUserId == null && fromUserIdUntilLeaf == null) {
			return AjaxResult.error(400, "Miss Parameter");
		}

		if (referralParentUserId != null) {
			if (!Objects.equals(loginedUserId, referralParentUserId)) {
				return AjaxResult.error(403, "Access Forbidden");
			}
			fttUserQuery.setReferralParentUserId(referralParentUserId);
		}

		if (fromUserIdUntilLeaf != null) {
			FttUser fromFttUser = fttUserService.findFttUserByUserId(fromUserIdUntilLeaf);
			if (!Objects.equals(loginedUserId, fromFttUser.getParentUserId())) {
				return AjaxResult.error(403, "Access Forbidden");
			}
			fttUserQuery.setParentUserIdPath(FttUserHelper.parentUserIdPath(fromFttUser));
		}

		PageResult<FttUser> pageResult = fttUserService.findFttUsers(fttUserQuery, pageable);
		return AjaxResult.successData(pageResult);
	}

	@GetMapping("/api/fttusers/userId={userId}")
	public AjaxResult showFttUser(@PathVariable("userId") Long userId) {
		Long loginedUserId = TokenHelper.verifyToken();
		if (!Objects.equals(userId, loginedUserId)) {
			return AjaxResult.error(403, "Access Forbidden");
		}
		FttUser fttUser = fttUserService.findFttUserByUserId(userId);
		if (fttUser == null) {
			return AjaxResult.error(404, "Not Found");
		}
		return AjaxResult.successData(fttUser);
	}

	@GetMapping("/api/fttusers/referralCode={referralCode}")
	public AjaxResult showFttUserByReferralCode(@PathVariable("referralCode") String referralCode) {
		FttUser fttUser = fttUserService.findFttUserByReferralCode(referralCode);
		if (fttUser == null) {
			return AjaxResult.error(404, "邀请码不存在");
		}
		return AjaxResult.successData(fttUser);
	}

	@GetMapping("/api/fttusers/userId={userId}/referralsummary")
	public AjaxResult showFttUserReferralSummary(@PathVariable("userId") Long userId) {
		Long loginedUserId = TokenHelper.verifyToken();
		if (!Objects.equals(userId, loginedUserId)) {
			return AjaxResult.error(403, "Access Forbidden");
		}
		FttUser fttUser = fttUserService.findFttUserByUserId(userId);
		if (fttUser == null) {
			return AjaxResult.error(404, "Not Found");
		}

		FttUser referralParentFttUser = fttUserService.findFttUserByUserId(fttUser.getReferralParentUserId());
		FttUser parentFttUser = null;
		if (fttUser.getParentUserId() > 0) {
			parentFttUser = fttUserService.findFttUserByUserId(fttUser.getParentUserId());
		}
		Long referralChildCount = fttUserService.findFttUserCountByReferralParentUserId(userId);
		Long teamCount = fttUserService.findFttUserCountByParentUserIdPathLikeRight(FttUserHelper.parentUserIdPath(fttUser));
		List<FttUser> childFttUsers = fttUserService.findFttUsersByParentUserId(userId);

		Map<String, Object> userReferralSummaryMap = new HashMap<>(4);
		userReferralSummaryMap.put("referralParentFttUser", referralParentFttUser);
		userReferralSummaryMap.put("parentFttUser", parentFttUser);
		userReferralSummaryMap.put("referralChildCount", referralChildCount);
		userReferralSummaryMap.put("teamCount", teamCount);
		userReferralSummaryMap.put("childFttUsers", childFttUsers);

		return AjaxResult.successData(userReferralSummaryMap);
	}

	@PutMapping("/api/fttusers/userId={userId}/parents")
	public AjaxResult updateFttUserParents(@PathVariable("userId") Long userId, FttUser fttUserForm) {
		Long loginedUserId = TokenHelper.verifyToken();
		if (!Objects.equals(userId, loginedUserId)) {
			return AjaxResult.error(403, "Access Forbidden");
		}

		Long parentUserId = fttUserForm.getParentUserId();
		if (parentUserId == null) {
			return AjaxResult.error(400, "parentUserId must not be null");
		}

		FttUser fttUser = fttUserService.findFttUserByUserId(userId);
		if (fttUser == null) {
			return AjaxResult.error(404, "Not Found");
		}

		Long id = fttUser.getId();
		fttUserFacadeService.updateFttUserParents(id, parentUserId);

		return AjaxResult.success();
	}

	@PutMapping("/api/fttusers/userId={userId}/cardz")
	public AjaxResult updateFttUserCardz(@PathVariable("userId") Long userId, FttUser fttUserForm, @RequestParam("verificationCode") String verificationCode) {
		Long loginedUserId = TokenHelper.verifyToken();
		if (!Objects.equals(userId, loginedUserId)) {
			return AjaxResult.error(403, "Access Forbidden");
		}

		String cardzCellphone = fttUserForm.getCardzCellphone();
		if (StringUtils.isBlank(cardzCellphone)) {
			return AjaxResult.error(400, "cardzCellphone must not be null");
		}

		if (!RegexSnippetUtils.isCellphone_CN(cardzCellphone)) {
			return AjaxResult.error(400, "手机号格式错误");
		}

		FttCard20220715 fttCard20220715 = fttCard20220715Service.findFttCard20220715ByCellphone(cardzCellphone);
		if (fttCard20220715 == null) {
			return AjaxResult.error(400, "请输入正确的229套餐号码");
		}
		if (fttCard20220715.getState() != FttCard20220715.State.success) {
			return AjaxResult.error(400, "请确认229套餐号码的缴费状态");
		}

		FttUser cardzFttUser = fttUserService.findFttUserByCardzCellphone(cardzCellphone);
		if (cardzFttUser != null && !cardzFttUser.getUserId().equals(loginedUserId)) {
			return AjaxResult.error(400, String.format("该号码已经被用户%s绑定", RegexSnippetUtils.desensitizeCellphone_CN(cardzFttUser.getCellphone())));
		}

		if (!SmsSendUtils.verfySmsCode(cardzCellphone, verificationCode)) {
			return AjaxResult.error(400, "验证码错误");
		}

		FttUser fttUser = fttUserService.findFttUserByUserId(userId);
		if (fttUser == null) {
			return AjaxResult.error(404, "Not Found");
		}

		if (fttUser.getCardzState() != FttUser.CardzState.pending) {
			return AjaxResult.error(400, "只能绑定一次");
		}

		Long id = fttUser.getId();
		fttUserService.updateFttUserCardz(id, FttUser.CardzState.success, cardzCellphone);

		return AjaxResult.success();
	}

}
